﻿using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// HTTP 联网之类，数据缓存
    /// </summary>
    public class DataCacheMa
    {
        public static Dictionary<string, CacheInfo> cache = new Dictionary<string, CacheInfo>();
        private static List<string> removeKey = new List<string>();
        public static float defaultOutTime = 10f;
        public static int defaultUseCounter = 1;

        public static T Get<T>(string key) where T : class, new()
        {
            T t = null;
            if (cache.ContainsKey(key))
            {
                var info = cache[key];
                t = info.value as T;
                if (info.timeType == TimeType.UseCounter)
                {
                    info.useCounter++;
                    if (info.useCounter >= info.useMax)
                    {
                        cache.Remove(key);
                    }
                }
            }

            return t;
        }

        public static void SetData(string key, CacheInfo o)
        {
            if (cache.ContainsKey(key))
                cache.Remove(key);

            cache.Add(key, o);
        }

        public static void SetData(string key, object o)
        {
            if (cache.ContainsKey(key))
                cache.Remove(key);

            CacheInfo info = new CacheInfo();
            info.value = o;
            cache.Add(key, info);
        }

        public static void SetTimeOutData(string key, object o)
        {
            if (cache.ContainsKey(key))
                cache.Remove(key);

            CacheInfo info = new CacheInfo();
            info.time = defaultOutTime;
            info.timeType = TimeType.TimeOut;
            info.value = o;
            cache.Add(key, info);
        }

        public static void FixedUpdate()
        {
            foreach (var item in cache)
            {
                var info = item.Value;
                if (info.timeType != TimeType.TimeOut)
                    continue;

                if (Time.realtimeSinceStartup - info.timeCounter >= Time.time)
                {
                    //移除当前字典
                    removeKey.Add(item.Key);
                }
            }

            for (int i = 0; i < removeKey.Count; i++)
            {
                cache.Remove(removeKey[i]);
            }
        }

        public class CacheInfo
        {
            public object value;
            public TimeType timeType = TimeType.None;
            public float time;
            public float timeCounter;
            public int useMax;
            public int useCounter;
        }

        public enum TimeType
        {
            /// <summary>
            /// 没有
            /// </summary>
            None,

            /// <summary>
            /// 时间超时
            /// </summary>
            TimeOut,

            /// <summary>
            /// 使用次数
            /// </summary>
            UseCounter,
        }
    }
}